package modules

import (
	"io/ioutil"
	"os"
	"time"

	"github.com/prometheus/prometheus/storage"
	"github.com/prometheus/prometheus/tsdb"
)

// MockStorage temporary storage
type MockStorage struct {
	*tsdb.DB
	dir string
}

// Close delete temporary files when closed
func (s MockStorage) Close() error {
	if err := s.DB.Close();  err != nil {
		return err
	}
	return os.Remove(s.dir)
}

// NewMockStorage create temporary storage
func NewMockStorage(filepath string ) (storage.Storage, error) {
	dir, err := ioutil.TempDir(filepath, "mock_storage_")
	if err != nil {
		return nil, err
	}
	opts := tsdb.DefaultOptions()
	opts.MinBlockDuration = int64(24 * time.Hour / time.Millisecond)
	opts.MaxBlockDuration = int64(24 * time.Hour/ time.Millisecond)
	db, err := tsdb.Open(dir, nil, nil, opts)
	if err != nil {
		return nil , err
	}

	return MockStorage{DB: db, dir: dir}, nil
}

